package com.yoomiito.app.pay

import android.util.Log
import cn.droidlover.xdroidmvp.net.ApiException
import cn.droidlover.xdroidmvp.net.ApiSubscriber
import cn.droidlover.xdroidmvp.net.XApi
import com.yoomiito.app.R
import com.yoomiito.app.base.BaseActivity
import com.yoomiito.app.model.order.PayResultInfo
import com.yoomiito.app.net.YmApi
import com.yoomiito.app.ui.my.psw.SetPayPswActivity
import com.yoomiito.app.utils.L
import com.yoomiito.app.utils.ResUtil
import com.yoomiito.app.utils.YMToast
import com.yoomiito.app.utils.encrypt.AESUtils
import com.yoomiito.app.widget.PasswordView_1
import com.yoomiito.app.widget.TipDialog
import com.yoomiito.app.widget.dialog.PswInputDialog

abstract class BasePayUtils(val context: BaseActivity<*>?,var payResultListener: (PayResult) -> Unit) {
    lateinit var orderingInfo: OrderPayInfo
    /**
     * 支付方式弹窗
     */
    abstract fun showPayDialog(orderingInfo: OrderPayInfo)

    /**
     * 提示设置密码框
     */
    fun showSetPayPswTip() {
        val mTipDialog = TipDialog(context, TipDialog.TYPE_SELECT)
        mTipDialog?.setTopTipText(ResUtil.getString(R.string.my_tip))
        mTipDialog?.setTipText("为确保余额资金安全，请先设置千年艾支付密码")
        mTipDialog?.setSureText("马上设置")
        mTipDialog?.setcancleText("取消")
        mTipDialog?.setDialogCallback(object : TipDialog.Dialogcallback {
            override fun btnConfirm() {
                SetPayPswActivity.start(context)
            }

            override fun cancel(): Boolean = false

        })
        mTipDialog?.show()
    }

    fun showPsw() {
        val mPswInputDialog = PswInputDialog(context!!)
        mPswInputDialog?.setTextChangedListener(object : PasswordView_1.TextChangedListener() {
            override fun textChanged(changeText: CharSequence) {

            }

            override fun textCompleted(text: CharSequence) {//余额支付
                mPswInputDialog.dismiss()
                context.showLoading()
                NewPayInfo(orderingInfo.orderInfo.id,
                        0,
                        0,
                        if(orderingInfo.deductMoneyPay==0) orderingInfo.orderInfo.amount_paid else orderingInfo.moneyPay,
                        orderingInfo.goodsType,//订单类型
                         AESUtils.rsaEncrypt(text.toString()),
                        orderingInfo.deductMoneyPay
                ).let { info ->
                    pay(info)
                }
            }

            override fun forgetPsw() {
                mPswInputDialog?.dismiss()
            }
        })
        mPswInputDialog?.show()
    }

    fun pay(payInfo:NewPayInfo) {
        L.i("支付金额: \nid:${payInfo.orderId} \nwx:${payInfo.wx} \nali:${payInfo.ali} \naccount:${payInfo.account}" +
                " \norderType:${payInfo.orderType} \npsw:${payInfo.psw} \ndeduction_account:${payInfo.deduction_account}")
        YmApi.getYmService()
                .multipPay(payInfo.orderId, payInfo.wx, payInfo.ali, payInfo.account, payInfo.orderType, payInfo.psw, payInfo.deduction_account.toString())
                .compose(context?.bindToLifecycle())
                .compose(XApi.getApiTransformerData())
                .compose(XApi.getScheduler())
                .subscribe(object : ApiSubscriber<PayResultInfo>() {
                    override fun onSuccess(payResultInfo: PayResultInfo) {
                        if ("accountpay" == payResultInfo.pay_type) {
                            payResultListener(PayResult(PayResult.PaySuccess,PayResult.AccountPay))
//                            val eventMessage = EventMessage()
//                            eventMessage.code = AllCode.Success
//                            context?.payResult(eventMessage)
                        } else {
                            context?.dismissLoading()
                            payResultListener(PayResult(PayResult.Paying,payResultInfo.pay_type,payResultInfo.out_trade_no))
//                            context?.mQueryOrderID = payResultInfo.out_trade_no
//                            context?.pay_type = payResultInfo.pay_type
                            if ("wxpay" == payResultInfo.pay_type) {
                                PayTypeUtils.wxPay(payResultInfo.data)
                            } else {
                                PayTypeUtils.aliPay(context, payResultInfo.data.alipay_order)
                            }
                        }
                    }

                    override fun onFail(error: ApiException) {
                        YMToast.showText(error.msg)
                        context?.dismissLoading()
                        payResultListener(PayResult(PayResult.PayFail, "", "",error.code,error.msg))

//                        if (error.code == ApiException.PAY_PSW_ERROR) {
//                            context?.error(true, ResUtil.getString(R.string.psw_error))
//                        } else if (error.code == ApiException.BALANCE_INSUFFICIENT) {
//                            context?.error(ResUtil.getString(R.string.balance_poor))
//                        } else if (error.code == ApiException.YOUMI_INSUFFICIENT) { //优米数量不足
//                            context?.error(error.msg)
//                            context?.showLoading()
////                            getRemain()
//                        } else {
//                            context?.error(false, "")
//                            val eventMessage = EventMessage()
//                            eventMessage.code = AllCode.Fail
//                            context?.payResult(eventMessage)
//                        }
                    }
                })
    }
}